import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Hashtable;
import java.util.Scanner;

/**
 * 
 */

/**
 * @description 
 * 
 * @author vihuynh, k7ho
 *
 */
public class Lookup {
	final static String MSG_USAGE = "Usage: %s indexfile\n";
	private String[] willyKoswara;
	private Hashtable<String, Hashtable<String, Integer>> hashTbl;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		if (args.length < 1 ) {
			System.out.printf(MSG_USAGE,Lookup.class.getName());
			return ;
		}
		else {
			Lookup lookup = new Lookup();
			try {
				lookup.ReadFile(args[0]);
				
				Scanner in = new Scanner(System.in);
				System.out.println("Enter keyword query (blank line to exit the program): ");
				String temp = in.nextLine();
				while(!temp.equals("")){
					lookup.prompt(temp);
					System.out.println("Enter keyword query (blank line to exit the program): ");
					temp = in.nextLine();
				}
				
				System.out.println("Okay, goodbye. -_-'");
				//System.out.println(" (^-^) <(''<) (>'')> t(''t) Q(''Q) ");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	private void prompt(String willy) {
		
		willyKoswara = willy.split(" ");
		
		Hashtable <String, Hashtable<String, Integer>> tbl =
			(Hashtable <String, Hashtable<String, Integer>> )hashTbl;
		for (String str: willyKoswara){
			System.out.printf("\"%s\" stems to --> \"%s\":",
					willy, (str = Keyword.makeKeyword(willy)));
			
			int count = 0;
			if(hashTbl.containsKey(str)){
				System.out.printf("  found in %d web pages.\n", hashTbl.get(str).size());
				
				//for(Hashtable <String, Hashtable<String, Integer>> blah : hashTbl.get(str))
				for (int i = 0; i < hashTbl.get(str).size();i++ ){
					System.out.println();
				}
				count = hashTbl.get(str).size();
			} else { 
				System.out.printf("  found in %d web pages.\n", 0);
				System.out.printf("RESULTS: %d documents match all query keywords.\n", count);
			}	
		}
	}
	
	@SuppressWarnings("unchecked")
	public void ReadFile(String filePath) throws IOException, ClassNotFoundException {
		FileInputStream fis = new FileInputStream(filePath);
		BufferedInputStream bis = new BufferedInputStream(fis);
		ObjectInputStream ois = new ObjectInputStream(bis);
		
		hashTbl = (Hashtable<String, Hashtable<String, Integer>>) ois.readObject();
		
		System.out.println("Reading index file " + filePath + "... Contains " + hashTbl.size() + 
				" keywords.");
	}

}
